/*
XPTracker - Alternative Agile Tracking Tool
Copyright (C) 2006-2009  Stephen Starkey

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
package org.xptracker.services;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.xptracker.domain.CurrentUserProvider;
import org.xptracker.domain.Domain;
import org.xptracker.domain.User;
import org.xptracker.persistence.PersistenceManager;
import org.xptracker.util.ThreadLocalCleaner;

@Singleton
public class ThreadLocalCurrentUserProvider implements CurrentUserProvider {
  private final ThreadLocal<String> currentUserId = ThreadLocalCleaner.registerForCleanup(new ThreadLocal<String>());

  private final ThreadLocal<User> currentUser =
      ThreadLocalCleaner.registerForCleanup(new ThreadLocal<User>() {
        protected User initialValue() {
          return domain.fetchUser(currentUserId.get());
        }
      });

  private Domain domain;

  @SuppressWarnings({"UnusedDeclaration"})
  @Inject
  private void setPersistenceManager(PersistenceManager mgr) {
    this.domain = new Domain(mgr);
  }

  public User getCurrentUser() {
    return getCurrentUser(false);
  }

  public User getCurrentUser(boolean refresh) {
    if (refresh) {
      currentUser.remove();
    }
    return currentUser.get();
  }

  public void setCurrentUser(String userId) {
    currentUserId.set(userId);
  }
}
